package com.dman.multi.proto;


public class ProtocolHandlerFactory {
	private String packageName;
	private static ProtocolHandlerFactory protoFactory; 
	
	// decipher the package name of this class
	private ProtocolHandlerFactory(){
		String cl = ProtocolHandler.class.getName();
		packageName = "";
		if(cl.lastIndexOf('.') > 0)
			packageName = cl.substring(0, cl.lastIndexOf('.') + 1);
	}
	
	// ensure access to the factory object using a singleton
	public static ProtocolHandlerFactory getInstance(){
		if(protoFactory == null){
			synchronized (ProtocolHandlerFactory.class) {
				if(protoFactory == null)
					protoFactory = new ProtocolHandlerFactory();
			}
		}
		
		return protoFactory;
	}
	
	// this is the object that this factory produces
	public ProtocolHandler getProtocolHandler(String proto) {
		
		// this converts protocol to all upper case
		proto = proto.toUpperCase();
		proto += "ProtocolHandler";
		
		// lookup the class name with reflection
		ProtocolHandler ph = null;
		try {
			ph = (ProtocolHandler) Class.forName(packageName + proto).newInstance();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		
		return ph;
	}
}
